// src/components/User/Invites.jsx
import { useState, useEffect } from 'react'
import { Table, Button, Card, Tag, message, Modal, Typography } from 'antd'
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { userAPI } from '@/api/user'

const { Text } = Typography;
const { confirm } = Modal;

const columns = [
  {
    title: '邀请码',
    dataIndex: 'code',
    render: text => <span style={{ fontWeight: 500 }}>{text}</span>
  },
  {
    title: '状态',
    dataIndex: 'status',
    render: status => (
        <Tag color={status === 'active' ? 'success' : 'default'}>
          {status === 'active' ? '未使用' : status === 'used' ? '已使用' : '已过期'}
        </Tag>
    )
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    render: text => new Date(text).toLocaleString()
  },
  {
    title: '使用时间',
    dataIndex: 'usedAt',
    render: text => text ? new Date(text).toLocaleString() : <span style={{ color: '#999' }}>未使用</span>
  }
]

export default function Invites() {
  const [loading, setLoading] = useState(false)
  const [data, setData] = useState({ list: [], total: 0 })
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10 })
  const [userInfo, setUserInfo] = useState(null)
  const [magicLoading, setMagicLoading] = useState(false)

  // 加载用户信息
  const loadUserInfo = async () => {
    try {
      const res = await userAPI.getInfo()
      // 根据后端返回结构调整
      setUserInfo(res.data.data) // 假设后端返回 { data: { ... } }
    } catch (error) {
      console.error("用户信息加载失败", error)
      // 模拟用户数据
      setUserInfo({
        id: 1,
        username: "test_user",
        email: "user@example.com",
        userRole: "normal",
        userLevel: 2,
        magicValue: 5000,
        uploadAmount: 10737418240,
        downloadAmount: 5368709120,
        shareRatio: 2.0,
        seedCount: 5,
        seedDuration: 168,
        lastLoginTime: "2024-01-01T12:00:00",
        status: "active"
      })
    }
  }

  // 加载邀请码列表
  const loadData = async () => {
    try {
      setLoading(true)
      const res = await userAPI.getInviteCodes({
        page: pagination.current,
        size: pagination.pageSize
      })

      // 根据后端返回结构调整
      const responseData = res.data.data;

      setData({
        list: responseData.records,
        total: responseData.total
      })

    } catch (error) {
      message.error('邀请码加载失败: ' + (error.response?.data?.message || error.message))
      console.error('邀请码加载失败', error)
    } finally {
      setLoading(false)
    }
  }

  // 生成邀请码（使用魔力值兑换）
  const generateInviteCode = async () => {
    if (!userInfo) return;

    try {
      setMagicLoading(true);

      // 检查魔力值是否足够
      if (userInfo.magicValue < 2000) {
        message.error(`魔力值不足，需要2000魔力值，当前仅有${userInfo.magicValue}`);
        return;
      }

      // 确认兑换
      confirm({
        title: '确认使用魔力值兑换邀请码？',
        icon: <ExclamationCircleOutlined />,
        content: `此操作将消耗2000魔力值，您当前有${userInfo.magicValue}魔力值。`,
        okText: '确认兑换',
        cancelText: '取消',
        onOk: async () => {
          try {
            // 调用API生成邀请码
            await userAPI.createInviteCodeByMagic();
            message.success('邀请码生成成功');

            // 更新用户魔力值
            setUserInfo({ ...userInfo, magicValue: userInfo.magicValue - 2000 });

            // 刷新邀请码列表
            loadData();
          } catch (error) {
            message.error(error.response?.data?.message || '兑换失败');
            console.error('兑换邀请码失败', error);
          }
        }
      });
    } catch (error) {
      message.error(error.response?.data?.message || '操作失败');
      console.error('生成邀请码失败', error);
    } finally {
      setMagicLoading(false);
    }
  }

  useEffect(() => {
    loadUserInfo();
    loadData();
  }, [pagination])

  // 渲染用户信息
  const renderUserInfo = () => {
    if (!userInfo) return null;

    return (
        <div style={{ marginBottom: 16, backgroundColor: '#f5f5f5', padding: '12px 24px', borderRadius: 8 }}>
          <Text strong>当前状态：</Text>
          <Text type="secondary" style={{ margin: '0 16px 0 8px' }}>
            魔力值：<Text style={{ color: '#52c41a' }}>{userInfo.magicValue}</Text>
          </Text>
          <Text type="secondary">
            生成邀请码需要消耗<Text style={{ color: '#f5222d' }}>2000</Text>魔力值
          </Text>
        </div>
    )
  }

  return (
      <Card
          title="邀请码管理"
          bordered={false}
          extra={
            <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={generateInviteCode}
                loading={magicLoading}
                disabled={!userInfo || userInfo.magicValue < 2000}
            >
              生成新邀请码
            </Button>
          }
      >
        {renderUserInfo()}

        <Table
            columns={columns}
            rowKey="id"
            dataSource={data.list}
            pagination={{
              ...pagination,
              total: data.total,
              showSizeChanger: true,
              onChange: (page, size) => setPagination({ current: page, pageSize: size })
            }}
            loading={loading}
        />
      </Card>
  )
}